<template>
  <el-row class="mx__20 px-20 bg-white">
    <el-col class="current-content-style">
      <el-row class="py-20">
        <el-col>
          <el-row type="flex" justify="left" :gutter="0">
            <el-input v-model="searchValue" style="width: 200px" placeholder="按水表编号查询"></el-input>
            <el-button type="primary" @click="searchWaterMeter">查询</el-button>
            <el-button plain type="success" @click="getWaterMeterQueryPage">重置</el-button>
            <el-button plain type="danger" @click="isShowUploadModal = true">导入</el-button>
            <el-button plain type="info" @click="downLoadHandler2">导出</el-button>
            <el-button plain type="success" @click="downLoadHandler">下载模板</el-button>
            <el-button plain type="primary" @click="isShowAddWaterMeterModal = true">添加</el-button>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-table
            stripe
            hover
            :data="tableData"
            style="width: 100%"
            :header-row-class-name="
              ({ row, rowIndex }) => {
                if (rowIndex === 0) return 'table-header-bg'
              }
            "
          >
            <el-table-column prop="waterNumber" label="水表编号" width="100"> </el-table-column>
            <el-table-column prop="waterModel" label="水表型号" width="180"> </el-table-column>
            <el-table-column prop="customerName" label="开户人" width="120"> </el-table-column>
            <el-table-column prop="waterMaxMeter" label="最大计量" width="80"> </el-table-column>
            <el-table-column prop="waterInitialCount" label="初始度数" width="80"> </el-table-column>
            <el-table-column prop="waterInstallAddress" label="安装地址">
              <template v-slot="scope">
                <span>
                  {{
                    scope.row.waterInstallAddress
                      ? scope.row.waterInstallAddress + '-' + scope.row.waterInstallAddressInfo
                      : '空'
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="waterInstallTime" label="安装日期" width="100">
              <template v-slot="scope">
                {{ getUserFormatDate(scope.row.waterInstallTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="billingName" label="计费类型" width="150"> </el-table-column>
            <el-table-column label="操作" width="80">
              <template v-slot="scope">
                <i
                  @click="
                    $router.push({ path: '/home/waterquality_detail', query: { waterNumber: scope.row.waterNumber } })
                  "
                  class="text-20 curser-pointer text-primary mr-20 el-icon-s-comment"
                ></i>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row class="my-20" style="text-align: right">
        <el-col :span="24">
          <el-pagination
            v-show="total !== 1"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-col>
      </el-row>
    </el-col>
    <el-dialog title="选择要导入的水表数据文件" :visible.sync="isShowUploadModal" width="30%">
      <el-upload action="/" :auto-upload="false" :on-change="changeFileHandler" :file-list="fileList">
        <el-button size="small" type="primary">选择文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传一个xls/xlss文件</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="escUploadHandler">取 消</el-button>
        <el-button type="primary" @click="uploadFileHandler">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog @close="handler_close" title="添加水表" :visible.sync="isShowAddWaterMeterModal" width="30%">
      <el-form ref="editform" :model="editForm" :rules="rules" label-width="80px">
        <el-form-item label="水表类型" prop="waterTypeId">
          <el-select v-model="editForm.waterTypeId">
            <el-option
              v-for="item in waterTypeArr"
              :key="item.waterTypeId"
              :label="item.waterModel"
              :value="item.waterTypeId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="初始读数" prop="waterInitialCount">
          <el-input type="text" v-model.number="editForm.waterInitialCount">
            <template slot="append">度</template>
          </el-input>
        </el-form-item>
        <el-form-item label="水表编号" prop="waterNumber">
          <el-input placeholder="请输入水表编号" type="text" v-model.trim="editForm.waterNumber"> </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="escAddWaterMeterHandler">取 消</el-button>
        <el-button type="primary" @click="addWaterMeterHandler('editform')">确 定</el-button>
      </span>
    </el-dialog>
  </el-row>
</template>

<script>
// 水表管理
import { getUserFormatDate } from '@/utils/dateUtils'

import {
  getWaterMeterList,
  downloadWaterMeterModel,
  downloadWaterMeterExecl,
  uploadWaterMeterExecl,
  getWaterMeterDetailInfo,
  getWaterTypeList,
  addWaterMeterInfo
} from '@/config/api'
// import axios from 'axios'
export default {
  data() {
    return {
      pageSizes: [5, 10, 15, 20],
      pageSize: 5,
      total: 0,
      currentPage: 1,
      searchValue: '',
      tableData: [],
      list: [], // 请求回来的默认数据
      uploadFile: '', // 导入的文件
      isShowUploadModal: false, // 导入水表modal
      isShowAddWaterMeterModal: false, // 添加水表
      fileList: [], // 文件列表
      billingType: [],
      // 添加水表的form对象
      editForm: {
        waterTypeId: '', //水表类型ID
        waterInitialCount: 0, // 初始度数
        waterNumber: '' // 水表编号
      },
      rules: {
        waterTypeId: [{ required: true, message: '请选择水表类型', trigger: 'change' }],
        waterInitialCount: [{ required: true, message: '请输入水表初始度数', trigger: 'blur' }],
        waterNumber: [{ required: true, message: '请输入水表编号', trigger: 'blur' }]
      },
      waterTypeArr: [] //水表类型数组
    }
  },

  created() {
    this.getWaterMeterQueryPage()
    this.getWaterType()
  },
  methods: {
    getUserFormatDate(v) {
      return getUserFormatDate(v)
    },
    handler_close() {
      this.$refs['editform'].resetFields()
    },
    // 取消添加水表
    escAddWaterMeterHandler() {
      this.isShowAddWaterMeterModal = false
    },
    // 添加水表
    addWaterMeterHandler() {
      this.$refs.editform.validate(value => {
        if (value) {
          addWaterMeterInfo({
            ...this.editForm
          }).then(res => {
            if (res.code === 200) {
              this.isShowAddWaterMeterModal = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.getWaterMeterQueryPage()
            } else {
              this.$message({
                message: '添加失败',
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },

    // 获取水表类型
    getWaterType() {
      getWaterTypeList().then(res => {
        if (res.code === 200) {
          console.log(res)
          this.waterTypeArr = res.data
        } else {
          this.$message({
            message: '获取水表类型失败',
            type: 'error'
          })
        }
      })
    },
    // 查询水表
    searchWaterMeter() {
      getWaterMeterDetailInfo({ waterNumber: this.searchValue }).then(res => {
        // console.log(res)
        if (res.code === 200) {
          this.tableData = []
          let obj = {
            associatedList: res.data.associatedList,
            ...res.data.billingBasePrice,
            ...res.data.customer,
            ...res.data.waterMeter,
            ...res.data.waterType
          }
          this.tableData.push(obj)
          this.searchValue = ''
          this.total = this.tableData.length
        }
      })
    },
    // 确定上传导入的文件的函数
    uploadFileHandler() {
      let myfromData = new FormData()
      myfromData.append('file', this.uploadFile)
      uploadWaterMeterExecl(myfromData).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message({
            message: '导入成功'
          })
          this.isShowUploadModal = false
          this.fileList = []
          this.uploadFile = ''
          this.getWaterMeterQueryPage() //重新获取最新数据
        }
      })
    },
    // 取消上传时的函数
    escUploadHandler() {
      this.isShowUploadModal = false
      this.fileList = []
      this.uploadFile = ''
    },
    // 选择文件时的函数
    changeFileHandler(file, fileList) {
      // console.log(fileList)
      const isExecl =
        file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.raw.type === 'application/vnd.ms-excel'

      if (!isExecl) {
        this.$message.error('上传文件只能是 xls, xlsx 格式!')
        this.fileList = []
      } else {
        this.uploadFile = file.raw
        fileList.length === 2 && (this.fileList = [fileList[1]])
      }
      // console.log(this.uploadFile)
    },

    // 导出水表数据
    downLoadHandler2() {
      downloadWaterMeterExecl()
        .then(res => {
          const link = document.createElement('a')
          const blob = new Blob([res], { type: 'application/vnd.ms-excel;charset=utf-8' })
          link.href = URL.createObjectURL(blob)
          link.download = '水表数据.xlsx'
          link.click()
          link.remove()
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 下载水表导入的模板
    downLoadHandler() {
      downloadWaterMeterModel()
        .then(res => {
          // console.log(res)
          const link = document.createElement('a')
          const blob = new Blob([res], { type: 'application/vnd.ms-excel;charset=utf-8' })
          link.href = URL.createObjectURL(blob)
          link.download = 'waterMeter模板文件.xlsx'
          link.click()
          link.remove()
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 获取一页水表信息
    getWaterMeterQueryPage() {
      getWaterMeterList({ pageNum: this.currentPage, pageSize: this.pageSize }).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.list = res.data.list
          this.tableData = []
          res.data.list.forEach(el => {
            let obj = {
              associatedList: el.associatedList,
              ...el.billingBasePrice,
              ...el.customer,
              ...el.waterMeter,
              ...el.waterType
            }
            this.tableData.push(obj)
          })
          this.total = res.data.total
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.getWaterMeterQueryPage()
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.getWaterMeterQueryPage()
    }
  }
}
</script>

<style scoped>
/* /deep/ .table-header-bg > th {
  background-color: rgba(233, 182, 226, 0.534) !important;
} */
</style>
